﻿<%@ WebHandler Language="C#" Class="ContainerHoldOrReleaseReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 批次暂停释放查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.4.26
 **/

public class ContainerHoldOrReleaseReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT f.factoryname,cci.containername,cci.mfgordername,cci.productname,cci.productdescription,cci.workflowstepname,
       DECODE(cci.containertype,7,'单件批次',2,'数量批',3,'子序号批') containertype,cci.qty,
       DECODE(cci.ishold,1,'已暂停','已释放') ishold,
       DECODE(cci.containerstatus,2,'已关闭','未关闭') isclosed,
       cci.fromworkcentername,
       t.opertype,t.createdate,e.fullname,
       cci.productrevision,p1.productrevision new_productrevision,
       cci.workflowrevision,wf1.workflowrevision new_workflowrevision,op.operreason
FROM (
  SELECT op.containerid,MAX(op.createdate) createdate,'释放' opertype
  FROM opercontainerrecord op
  LEFT JOIN containercurrentinfo cci ON cci.containerid = op.containerid
  WHERE cci.ishold = 0 AND op.operreason = '产品工艺变更释放' AND op.opertype = '3' ";

        //主制分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //主制工区
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cci.fromworkcenterid = '{0}'", jObject["workcenterid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //工艺员
        if (jObject["gongyiyuan"] != null && jObject["gongyiyuan"].ToString() != "")
        {
            sql += string.Format(" AND cci.techniqueemployeeid = '{0}'", jObject["gongyiyuan"].ToString());
        }

        //推送时间
        if (jObject["createdate"] != null && jObject["createdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["createdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND op.createdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND op.createdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //批次状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            if (jObject["status"].ToString() == "已暂停")
            {
                sql += " AND cci.ishold = 1 ";
            }
            else
            {
                sql += " AND cci.ishold = 0 ";
            }
        }

        //批次是否关闭
        if (jObject["isclosed"] != null && jObject["isclosed"].ToString() != "")
        {
            if (jObject["isclosed"].ToString() == "已关闭")
            {
                sql += " AND cci.containerstatus = 2 ";
            }
            else
            {
                sql += " AND NVL(cci.containerstatus,0) <> 2 ";
            }
        }

        sql += @"
  GROUP BY op.containerid

  UNION ALL 

  SELECT op.containerid,MAX(op.createdate) createdate,'暂停' opertype
  FROM opercontainerrecord op
  LEFT JOIN containercurrentinfo cci ON cci.containerid = op.containerid
  WHERE op.operreason = '产品工艺变更暂停' AND op.opertype = '2' ";

        //主制分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //主制工区
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cci.fromworkcenterid = '{0}'", jObject["workcenterid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //推送时间
        if (jObject["createdate"] != null && jObject["createdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["createdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND op.createdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND op.createdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //工艺员
        if (jObject["gongyiyuan"] != null && jObject["gongyiyuan"].ToString() != "")
        {
            sql += string.Format(" AND cci.techniqueemployeeid = '{0}'", jObject["gongyiyuan"].ToString());
        }

        //批次状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            if (jObject["status"].ToString() == "已暂停")
            {
                sql += " AND cci.ishold = 1 ";
            }
            else
            {
                sql += " AND cci.ishold = 0 ";
            }
        }

        //批次是否关闭
        if (jObject["isclosed"] != null && jObject["isclosed"].ToString() != "")
        {
            if (jObject["isclosed"].ToString() == "已关闭")
            {
                sql += " AND cci.containerstatus = 2 ";
            }
            else
            {
                sql += " AND NVL(cci.containerstatus,0) <> 2 ";
            }
        }

        sql += @"
  GROUP BY op.containerid
) t
LEFT JOIN opercontainerrecord op ON op.containerid = t.containerid AND op.createdate = t.createdate
LEFT JOIN containercurrentinfo cci ON cci.containerid = op.containerid
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
LEFT JOIN product p ON p.productid = cci.productid
--LEFT JOIN employee e ON e.employeeid = op.operatorid
LEFT JOIN employee e ON e.employeeid = cci.techniqueemployeeid
LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
LEFT JOIN product p1 ON p1.productid = pb.revofrcdid --推送件号
LEFT JOIN workflow wf ON wf.workflowid = cci.workflowid
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
LEFT JOIN workflow wf1 ON wf1.workflowid = wfb.revofrcdid
ORDER BY cci.containername
";
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["factoryname"].Caption = "主制分厂";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["productname"].Caption = "零件图号";
        dtResult.Columns["productdescription"].Caption = "零件名称";
        dtResult.Columns["workflowstepname"].Caption = "当前工序";
        dtResult.Columns["containertype"].Caption = "批次类型";
        dtResult.Columns["qty"].Caption = "在制数";
        dtResult.Columns["ishold"].Caption = "批次当前状态";
        dtResult.Columns["isclosed"].Caption = "批次是否关闭";
        dtResult.Columns["createdate"].Caption = "推送时间";
        dtResult.Columns["fromworkcentername"].Caption = "主制工区";
        dtResult.Columns["fullname"].Caption = "工艺员";
        dtResult.Columns["opertype"].Caption = "类型";
        dtResult.Columns["productrevision"].Caption = "当前件号版本";
        dtResult.Columns["new_productrevision"].Caption = "推送件号版本";
        dtResult.Columns["workflowrevision"].Caption = "当前工艺版本";
        dtResult.Columns["new_workflowrevision"].Caption = "推送工艺版本";
        dtResult.Columns["operreason"].Caption = "暂停原因";

        ExportHelper.ExportExcel(dtResult, "批次暂停释放查询报表");
    }
}